<?php

namespace App\Admin\Forms\Mp;

use App\Admin\Renderable\CircleRender;
use App\Lib\WeApp\WeApp;
use App\Models\Circle\WxCircle;
use App\Wen\Utils\AdminUtils;
use App\Wen\Utils\Settings;
use DateTime;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Crontab\Models\Crontabs;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Widgets\Tooltip;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class FreePublishNoticeForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $circle_range = AdminUtils::_multipleSelectTable_order_process('selectTable:FreePublishNoticeForm:app_mp_free_publish_circle_range', $input['app_mp_free_publish_circle_range']);

        $circle_range_ = [];
        if(_empty_($circle_range)){

        }else{
            if(is_string($circle_range)){
                $circle_range = explode(',', $circle_range);
            }
            if(is_array($circle_range) && !_empty_($circle_range)){
                foreach ($circle_range as $circle_id){
                    if(!_empty_($circle_id) && $circle_id > 0){
                        $circle_range_[] = $circle_id;
                    }
                }
            }
        }

        Settings::set('app_mp_free_publish_tenant_alone', $input['app_mp_free_publish_tenant_alone']);
        Settings::set('app_mp_free_publish_frequency', $input['app_mp_free_publish_frequency']);
        Settings::set('app_mp_free_publish_user_range', $input['app_mp_free_publish_user_range']);
        Settings::set('app_mp_free_publish_duration', $input['app_mp_free_publish_duration']);
        Settings::set('app_mp_free_publish_post_range', $input['app_mp_free_publish_post_range']);
        Settings::set('app_mp_free_publish_time', $input['app_mp_free_publish_time']);
        Settings::set('app_mp_free_publish_circle_range', implode(',', $circle_range_));
        Settings::set('app_mp_free_publish_post_num', $input['app_mp_free_publish_post_num']);

        $crontab_id = get_site_meta('app_mp_free_publish_crontab_id', 'n');
        if($crontab_id > 0 && Crontabs::where('id', $crontab_id)->exists()){
            // 直接修改
            Crontabs::where('id', $crontab_id)->update([
                'schedule' => $this->generateCronExpression($input['app_mp_free_publish_time'], $input['app_mp_free_publish_frequency']),
                'status' => 'normal'
            ]);
        }else{
            // 创建
            DB::beginTransaction();
            try {
                // todo:
                $crontabs = new Crontabs();
                $crontabs->type = 'shell';
                $crontabs->title = '公众号自动推送';
                $crontabs->contents = '/www/server/php/80/bin/php artisan mp_free_publish:generate';
                $crontabs->schedule = $this->generateCronExpression($input['app_mp_free_publish_time'], $input['app_mp_free_publish_frequency']);
                $crontabs->sleep = 0;
                $crontabs->maximums = 0;
                $crontabs->executes = 0;
                $crontabs->timeout = 0;
                $crontabs->begin_at = current_time();
                $crontabs->end_at = '2090-01-01 00:00:00';
                $crontabs->weigh = 100;
                $crontabs->status = 'normal';
                $r = $crontabs->save();
                if($r){
                    update_site_meta('app_mp_free_publish_crontab_id', $crontabs->id, 'n');
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            } catch (\Exception $e) {
                DB::rollBack();
                _logger_(__file__, __line__, $e->getMessage());
            }
        }

        return $this->response()->success('保存成功')->location(admin_url('auth/crontabs'));
    }

    function generateCronExpression($time, $intervalDays) {
        // 解析输入时间
        list($hour, $minute, $second) = explode(':', $time);

        // 将时间提前 10 分钟
        $datetime = new DateTime();
        $datetime->setTime($hour, $minute, $second);
        $datetime->modify('-10 minutes');

        // 获取提前 10 分钟的小时和分钟
        $modifiedHour = $datetime->format('H');
        $modifiedMinute = $datetime->format('i');

        // 生成 cron 表达式
        $cronExpression = sprintf('%s %s */%d * *', $modifiedMinute, $modifiedHour, $intervalDays);

        return $cronExpression;
    }

    public function form()
    {
        $res34 = __system__paycode__tip__(34);
        Tooltip::make('.mini_global_admin_open_not_support_tip')
            ->bottom()
            ->title($res34['tip']);
        $crontab_id = get_site_meta('app_mp_free_publish_crontab_id', 'n');
        if($crontab_id > 0 && Crontabs::where('id', $crontab_id)->exists()) {
            $this->html(function () {
                return '<div style="background-color: transparent;color: #414750;padding: 10px;border-radius: 5px;">小提示：查看任务执行情况请去：<a href="' . admin_url('auth/crontabs') . '" target="_blank">定时任务列表</a></div>';
            }, '');
        }
        $this->html(function () use (&$res34){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">'.$res34['text'].'分站独立推：是指用一个公众号发送多篇内容，把对应的分站内容推送给对应分站的用户。<br/>多个公众号分站独立推送暂不在考虑范围</div>';
        }, '');
        $this->radio('app_mp_free_publish_tenant_alone', '分站')->options([1=>'所有一起推', 2=>'分站独立推'])->default(Settings::get('app_mp_free_publish_tenant_alone', 2));
        $this->divider();
        $this->html(function (){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">非常频繁的进行模板消息推送，极有可能被微信惩罚，所以需要你自己根据自己的用户规模，调整好策略。</div>';
        }, '');
        $this->radio('app_mp_free_publish_frequency', '频率')->options([1=>'1天1次', 2=>'2天1次', 3=>'3天一次', 4 => '4天一次', 5 =>'5天一次'])->default(Settings::get('app_mp_free_publish_frequency', 3));
        $this->radio('app_mp_free_publish_user_range', '用户范围')->options([1=>'最近10天在线', 2=>'最近20天在线', 3=>'最近30天在线', 4=>'最近40天在线', 5=>'最近50天在线'])->default(Settings::get('app_mp_free_publish_user_range', 3));
        $this->radio('app_mp_free_publish_duration', '通知时间')->options([1=>'1小时内通知完', 2=>'2小时内通知完', 3=>'3小时内通知完', 4=>'4小时内通知完', 5=>'5小时内通知完'])->default(Settings::get('app_mp_free_publish_duration', 2));
        $this->divider();
        $this->html(function (){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">这里是配置推送哪些笔记，比如 3天内获得喜欢数最多的10篇，注意这里是指：三天内获得的喜欢数，这是个增量，并非单纯按照笔记喜欢数进行排序</div>';
        }, '');
        $this->select('app_mp_free_publish_post_range', '推送对象')->options([
            1=>'1天-喜欢数', 2=>'2天-喜欢数', 3=>'3天-喜欢数', 4=>'4天-喜欢数', 5=>'5天-喜欢数',
            11=>'1天-评论数', 12=>'2天-评论数', 13=>'3天-评论数', 14=>'4天-评论数', 15=>'5天-评论数'
        ])->default(Settings::get('app_mp_free_publish_post_range', 3));

        $this->multipleSelectTable('app_mp_free_publish_circle_range', '限定圈子')
            ->title('圈子列表')
            ->max(100)
            ->from(CircleRender::make())
            ->model(WxCircle::class, 'id', 'circle_name', 'selectTable:FreePublishNoticeForm:app_mp_free_publish_circle_range')
            ->default(Settings::get('app_mp_free_publish_circle_range', ''));

        $this->number('app_mp_free_publish_post_num', '笔记数量')->help('一篇推文最多包含多少篇笔记')->default(Settings::get('app_mp_free_publish_post_num', 10));

        $this->divider();
        $this->html(function (){
            return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;">推文会提前10分钟生成，便于你修改，到达指定时间再推送给微信并直接发布，后续则是给对应的用户进行模板消息通知</div>';
        }, '');
        $this->time('app_mp_free_publish_time', '期待发布时间')->default(Settings::get('app_mp_free_publish_time', '20:00:00'));
    }
}
